<template>
  <div class="setting-container">
    <el-container class="setting-container">
      <el-aside width="220px" class="setting-aside">
        <el-button
          v-for="item in menuList"
          :key="item.name"
          :type="currentComponentName === item.name ? 'primary' : 'default'"
          class="setting-aside-btn"
          @click="handleMenu(item.name)"
          >{{ item.label }}</el-button
        >
      </el-aside>
      <el-main>
        <component :is="currentComponent" v-if="currentComponent" />
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, markRaw, ref, computed } from "vue";
import Shortcut from "./shortcut.vue";
import Screenshot from "./screenshot.vue";
import TestRequest from "@/views/test-request.vue";
import Translate from "./translate.vue";
import { invoke } from "@tauri-apps/api/core";

const currentComponentName = ref<string>("shortcut");
const currentComponent = computed(() => {
  switch (currentComponentName.value) {
    case "shortcut":
      return markRaw(Shortcut);
    case "screenshot":
      return markRaw(Screenshot);
    case "test-request":
      return markRaw(TestRequest);
    case "translate":
      return markRaw(Translate);
    default:
      return null;
  }
});

const menuList = [
  {
    name: "shortcut",
    label: "快捷键",
  },
  {
    name: "screenshot",
    label: "截屏",
  },
  {
    name: "translate",
    label: "翻译",
  },
  {
    name: "test-request",
    label: "网络请求",
  },
];

// 处理键盘事件
const handleKeyDown = async (event: KeyboardEvent) => {
  if (event.key === "Escape" || event.key === "Esc") {
    try {
      await invoke("close_current_window");
    } catch (e) {
      console.error("关闭窗口失败:", e);
    }
  }
};

onMounted(() => {
  handleMenu("shortcut");
  window.addEventListener("keydown", handleKeyDown);
});

onUnmounted(() => {
  window.removeEventListener("keydown", handleKeyDown);
});

function handleMenu(name: string) {
  currentComponentName.value = name;
}
</script>

<style scoped lang="scss">
.setting-container {
  height: 100vh;
  padding: 12px;
  border-radius: 20px;
  overflow: hidden;
}
.setting-container > .el-container {
  height: 100%;
}
.setting-aside {
  padding: 12px;
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 12px;
  .setting-aside-btn {
    width: 100%;
    margin-bottom: 12px;
    display: inline-flex;
    justify-content: center;
    margin-left: 0;
  }
}
.shortcut-form {
  max-width: 560px;
}
</style>
